<template>
  <div class="YLForm">
    <slot></slot>
  </div>
</template>
<script>
// 1.props  model  rules
// 2.validate()
export default {
  provide() {
    form: this;
  },
  name: 'YLForm',
  componentName: 'YLForm',
  // model 必填是为了统一的管理，统一的分发
  props: {
    model: { type: Object, required: true },
    rules: Object,
  },
  created() {
    this.fields = [];
    // 这样能解耦并且很快速的找到  formItem
    this.$on('yl.form.addField', (field) => {
      this.fields.push(fields);
    });
  },
  methods: {
    validate(cb) {
      // 全局校验方法
      // 执行内部所有的 formItem
      // $children 并不是很严谨
      // 如果用递归找子元素会很消耗性能
      // let tasks = this.$children
      //   .filter((formItem) => formItem.prop)
      //   .map((formItem) => formItem.validate());
      let tasks = this.fields.map((formItem) => formItem.validate());

      // 统一的检查校验结果
      Promise.all(tasks)
        .then(() => {
          cb(true);
        })
        .catch(() => {
          cb(false);
        });
    },
  },
};
</script>
